﻿'NEJO1
Imports System.ComponentModel
Imports System.Collections.ObjectModel
Imports System.Text
Imports System.Data  

Public Class CSGeneralEjecucion
   

Public Const __SINPARTIDAEJ__  As Integer = -1 

Public Structure structTotalesDistribPEJ
  Public MontoOperado         As Decimal 
  Public MontoDisponible      As Decimal 
  Public PorcentajeOperado    As Decimal 
  Public PorcentajeDisponible As Decimal 
End Structure



Public Function  ObtenerPSEnviadasDeBSO() As List(Of CTPartidaSolicitud)  
  Return BSO.LstPS.FindAll(Function(x) x.EstatusActualPS = CTPartidaSolicitud.enumEstatusPS.ENVIADA)
End Function

Public Function  ObtenerPAJEnviadasDeBSO() As List(Of CTPartidaAjuste)  
  return BSO.LstPAJ.FindAll(Function(x) x.Estatus = CTPartidaAjuste.enumEstatusPAJ.ENVIADA)
End Function

Public Function  ObtenerPAJAplicadaDeBSO() As List(Of CTPartidaAjuste)  
  return BSO.LstPAJ.FindAll(Function(x) x.Estatus = CTPartidaAjuste.enumEstatusPAJ.APLICADA)
End Function

Public Function ObtenerPajCompuestaEnviadas() As Object
 Dim  lstPAJCompuesta         As object

 Try
 
 Dim  lstPAJRecibidas  = New ObservableCollection(Of CTPartidaAjuste)(ObtenerPAJEnviadasDeBSO())
     
     lstPAJCompuesta  = From paj In lstPAJRecibidas Join pej In BSO.LstPEJ On paj.PartidaEJId Equals pej.PartidaEJId 
                                                    Join ps In BSO.LstPS  On pej.AncestrosPEJ.PSId Equals ps.PartidaSolId 
                        Select 
                              paj.SeleccionEJ,                              
                              paj.PartidaAjusteID,
                              paj.PartidaSolicitudId,
                              paj.PartidaEJId, 
                              paj.FecCreacion,       
                              paj.FecAplicacion,     
                              paj.CantidadAjus,
                              paj.Comentario,
                              ps.Tvng,
                              pej.Intermediario,
                              pej.Tasa,
                              pej.CantidadAsigInterm

   Return lstPAJCompuesta


  Catch ex As Exception

     Dim err As new CError()
     err.ATRAPADO = false  
     err.DESC_ERROR = ex.Message
     err.CODCLASE = "NEJO1"
     Throw err
  End Try

End Function








Public Function ObtenerPajCompuestaAplicada() As Object
 Dim  lstPAJCompuesta         As object

 Try
 
 Dim  lstPAJRecibidas  = New ObservableCollection(Of CTPartidaAjuste)(ObtenerPAJAplicadaDeBSO())
     
     lstPAJCompuesta  = From paj In lstPAJRecibidas Join pej In BSO.LstPEJ On paj.PartidaEJId Equals pej.PartidaEJId 
                                                    Join ps In BSO.LstPS  On pej.AncestrosPEJ.PSId Equals ps.PartidaSolId 
                        Select 
                              paj.SeleccionEJ,                              
                              paj.PartidaAjusteID,
                              paj.PartidaSolicitudId,
                              paj.PartidaEJId, 
                              paj.FecCreacion,       
                              paj.FecAplicacion,     
                              paj.CantidadAjus,
                              paj.Comentario,
                              ps.Tvng,
                              pej.Intermediario,
                              pej.Tasa,
                              pej.CantidadAsigInterm

   Return lstPAJCompuesta


  Catch ex As Exception

     Dim err As new CError()
     err.ATRAPADO = false  
     err.DESC_ERROR = ex.Message
     err.CODCLASE = "NEJO1"
     Throw err
  End Try

End Function


Public Function  ObtenerPSEnProcesoDeBSO() As List(Of CTPartidaSolicitud)  
  Return BSO.LstPS.FindAll(Function(x) x.EstatusActualPS = CTPartidaSolicitud.enumEstatusPS.EN_PROCESO)
End Function

Public Function ObtenerSubPEJDePS(ByRef pPS As CTPartidaSolicitud) As List(Of SubPej )

 Dim lstSubPEJ  = New  list(Of SubPej )
   
 For Each pej As CTPartidaEJ In pPS.LstPEJ
     lstSubPEJ.Add(pej.RegresarNuevoSubPEJ)
 Next

 If lstSubPEJ.Count > 0 then 
    Return lstSubPEJ
 Else 
    Return Nothing 
 End If


End Function

Public Function ObtenerPSLiberadaEnfoqueEJ() As list(Of CTPartidaSolicitud)
  Return BSO.LstPS.FindAll(Function(x) x.EstatusActualPS = CTPartidaSolicitud.enumEstatusPS.LIBERADA or _
                                       x.EstatusActualPS = CTPartidaSolicitud.enumEstatusPS.EN_DISTRIBUCION or _
                                       x.EstatusActualPS = CTPartidaSolicitud.enumEstatusPS.CERRADA)
End Function

Public Function ObtenerListaSubPEJEdicionXPS(ByRef ps As CTPartidaSolicitud, ByRef lstCatInterParam As List(Of CTParamIntermediario) ) As List (Of SubPej)


  Dim Intermediario As CTParamIntermediario = Nothing
  Dim idInter       As Integer = -1
  Dim lstSubPEJ     As List ( Of SubPej) = Nothing
 

  If not ps is Nothing then      
      
      lstSubPEJ =  ObtenerSubPEJDePS (ps) 

      If Not IsNothing( lstSubPEJ ) then 

          For Each sPej As SubPej in lstSubPEJ 
              idInter = sPej.Intermediario.IdIntermediario

              Intermediario  = lstCatInterParam.Find(Function (x) x.IdIntermediario = idInter)
              If not Intermediario is Nothing then 
                 sPej.Intermediario    = Intermediario
              End If

              Intermediario = Nothing 
              idInter = -1
          Next

      end if
      
           
   End If

   Return lstSubPEJ

End Function

Public Function ObtenerFechaIniPeriodoEJ() As String            
   Return  CSServiciosGenerales.ConvertirAFecha (   CFLServicioLocalSQLServerDB.ObtenerFechaPeriodoEJ () )     
End Function


Public Function ObtenerLstSimulacionBase(ByVal sFechaPeriodoEJ As String, _
                                         ByRef lstCatIntermediario As List(Of CTParamIntermediario), _
                                         ByRef MontoTotal As Decimal  ) As List (Of CTCorridaIntermediario) 

'Funcion que regresa una lista nueva con los datos base de la simulación


  Dim dt            As DataTable   
  Dim intermediario As CTParamIntermediario  
  Dim lstSimulacion  = New List   (Of  CTCorridaIntermediario )



   Try

     dt = CFLServicioLocalSQLServerDB.ObtenerSimulacionBaseA (sFechaPeriodoEJ) 
     
     'Se carga el intermediario del catálogo pasado por referencia
     For Each registro As DataRow In dt.Rows 
         Dim idIntermediario = registro("INTERMEDIARIO")         
         intermediario = lstCatIntermediario.Find(Function(x) x.IdIntermediario = idIntermediario)               
         lstSimulacion.Add (New CTCorridaIntermediario(intermediario,registro("CANTIDAD"),MontoTotal) )               
     Next

     Return  lstSimulacion

   Catch ex As CError 
      Throw ex
   End Try


End Function

Public Function ObtenerLstSimulacionBaseMenosEdicionIni(ByRef lstbaseSimulacion As List(Of CTCorridaIntermediario), _
                                                        ByRef lstsubpejSelec    As List(Of SubPej ), _
                                                        ByRef lstCatInter As List(Of CTParamIntermediario), _
                                                        ByRef MontoTotal As Decimal ) As List(Of CTCorridaIntermediario )

 Dim lstSimulacion = New  List(Of CTCorridaIntermediario ) 
 Dim simula As CTCorridaIntermediario = Nothing 
 Dim intermediario As CTParamIntermediario 

 


  
     'Crear la nueva lista Simulacion 
      For Each simulacion As CTCorridaIntermediario In  lstbaseSimulacion 
           Dim idInter As Integer = simulacion.Intermediario.IdIntermediario     
           intermediario = lstCatInter.Find (Function (x) x.IdIntermediario = idInter ) 
           lstSimulacion.Add (New CTCorridaIntermediario (intermediario ,simulacion.MontoOperado,MontoTotal  ) )
      Next


      If Not lstsubpejSelec is Nothing THEN 

     
        For Each subpegI As SubPej In  lstsubpejSelec 
           Dim idInter As Integer = subpegI.Intermediario.IdIntermediario    
           
           If  idInter > 0 then 

                simula  =   lstSimulacion.Find (Function(x) x.Intermediario.IdIntermediario = idInter) 
                If (simula.MontoOperado - subpegI.CantidadAsigInterm) <= 0 then 
                    lstSimulacion.Remove (simula)
                 Else
                    simula.MontoOperado -=  subpegI.CantidadAsigInterm
                End If


           End If
           
        Next
      End If


        Return lstSimulacion 

End Function


Public Function ObtenerLstSimulacionMasEdicion(ByRef lstSimulacion As List(Of CTCorridaIntermediario ), _ 
                                               ByRef lstSubPejEdit As List(Of SubPej), _
                                               ByRef lstCatInter   As List(Of CTParamIntermediario), _
                                               ByRef MontoTotal    As Decimal ) As List(Of CTCorridaIntermediario )

    Dim simula As CTCorridaIntermediario = Nothing 
    Dim intermediario As CTParamIntermediario 

    If Not lstSubPejEdit is Nothing 
    
         For Each subpegI As SubPej in lstSubPejEdit
             Dim idInter As Integer = subpegI.Intermediario.IdIntermediario     

             If idInter > 0 then
                    simula  =   lstSimulacion.Find (Function(x) x.Intermediario.IdIntermediario = idInter) 
                    If not simula is Nothing 
                       simula.MontoOperado += subpegI.CantidadAsigInterm  
                     else
                       intermediario = lstCatInter.Find (Function (x) x.IdIntermediario = idInter ) 
                       lstSimulacion.Add (New CTCorridaIntermediario (intermediario ,subpegI.CantidadAsigInterm, MontoTotal  ) )                                                                 
                    End If
             End If 


         Next
     End If



    Return lstSimulacion

End Function


Public Function ObtenerMontoTotalPS(ByVal fecha As date, ByRef sMsgError As String) As Decimal 
  return  CFLServicioLocalSQLServerDB.ObtenerMontoTotalPSEnperiodo (fecha.ToString ("yyyy-MM-dd"),sMsgError )
End Function


Public Function ObtenerMontoTotalPsXInter(ByRef lstSimulacion As List(Of CTCorridaIntermediario) ) As structTotalesDistribPEJ 


  Dim totales As structTotalesDistribPEJ 
  totales.MontoOperado         = 0 
  totales.MontoDisponible      = 0
  totales.PorcentajeOperado    = 0 
  totales.PorcentajeDisponible = 0 



        For Each corrida As CTCorridaIntermediario In lstSimulacion 
           
              totales.MontoOperado         += corrida.MontoOperado            
              totales.PorcentajeOperado    += corrida.PorcentActualOperado 
              totales.PorcentajeDisponible += corrida.PorcentDiferencia 
              totales.MontoDisponible      += corrida.MontoDisponible 
        Next

    Return  totales 
End Function



Public Function ObtenerPSCanceladasDesdeEJ() As Object 
 Dim filtroIdPS       = New StringBuilder ()
 Dim lstcancelPSEjec  = New  List(Of CTPSProcEject )
 Dim dtPSCancel            As DataTable 
 Dim lstPSCanCompuesta     As object

 Try

 '1) Generar filtro  y obtener info de cancelación 
    Dim lstPSCancel  As List(Of CTPartidaSolicitud ) = Nothing 
    lstPSCancel =   BSO.LstPS.FindAll(Function (x) x.EstatusActualPS = CTPartidaSolicitud.enumEstatusPS.CANCELADA)  
    

    For Each ps As CTPartidaSolicitud In lstPSCancel
        filtroIdPS.Append (ps.PartidaSolId)
        filtroIdPS.Append (",")        
    Next  

    If filtroIdPS.Length > 0 then 
       filtroIdPS.Remove (filtroIdPS.Length - 1,1)
       dtPSCancel =   CFLServicioLocalSQLServerDB.ObtenerPSProcEjectDB (filtroIdPS.ToString)

    else 
       Return Nothing 
    End If
    

    If dtPSCancel is Nothing then 
        return nothing 
    End If


    For Each reg As DataRow In dtPSCancel.Rows
        Dim cancelaEJEC = New CTPSProcEject ()

        With cancelaEJEC
            .IdPS           = reg("ID_PARTIDA_PS")
            .ObservaCancel  = reg("OBSERVA_CANCELACION")
            .HoraCancel     = reg("HORA_CANCELA")
        End With

        lstcancelPSEjec.Add( cancelaEJEC ) 

    Next


    lstPSCanCompuesta = From psCan In lstcancelPSEjec Join ps In BSO.LstPS  On psCan.IdPS   Equals ps.PartidaSolId  
                        select 
                        ps.PartidaSolId,
                        ps.Tvng,
                        ps.FecSol,
                        ps.FecLiq,
                        ps.Plazo,
                        ps.CantidadSol,
                        psCan.ObservaCancel, 
                        psCan.HoraCancel 
                                                                     

   Return lstPSCanCompuesta


  Catch ex As Exception
      Return Nothing 
     
  End Try

End Function








Public Function ObtenerMontoTolerancia() As Double 
   Dim sMsgError As String = ""
   Return  CFLServicioLocalSQLServerDB.ObtenerMontoTolerancia () 
End Function

Public Function ObtenerTotalPSDistribEnPEJ(ByRef ps As CTPartidaSolicitud) As Decimal 

 Dim lstPej    As List(Of CTPartidaEJ)
 Dim totalPEJs As Decimal  = 0 

 lstPej = ps.LstPEJ   
  
  For Each pej As CTPartidaEJ In   lstPej
     totalPEJs += pej.CantidadAsigInterm 
  Next

 Return totalPEJs


End Function

Public Function ObtenerIntermediariosEnUtilizados(ByRef idBSO As Long) As List(Of long)
 Dim lstIdInterUtilizados = New List(Of long)
 Dim dt As DataTable = Nothing 
     
 dt = CFLServicioLocalSQLServerDB.ObtenerIntermediariosUtilizadosDB  (idBSO )

 'Cuando se obtuvo una excepción al consultar la BD
 If dt is Nothing then 
    Return lstIdInterUtilizados 'Regresa lista Vacia
 End If
  
 For Each registro As DataRow  In dt.Rows 
     lstIdInterUtilizados.Add(registro("INTERMEDIARIO"))    
 Next
 
 Return lstIdInterUtilizados   

End Function




Public Function GuardarPEJ(ByRef lstEditadaPEJ      As List(Of SubPej), _
                           ByRef lstIDEliminadasPEJ As List(Of Long), _
                           ByRef psSel              As CTPartidaSolicitud, _
                           byref lstFallas as List(Of StringBuilder ), _
                           Optional ByRef eventoBit As CSBitEvento = Nothing) As Boolean


 

 Dim lstINSERT as IEnumerable      = From subpejElement As SubPej in lstEditadaPEJ Where subpejElement.PartidaEJId = __SINPARTIDAEJ__ And subpejElement.Intermediario.IdIntermediario <> 0
 Dim lstUPDATE as IEnumerable      = From subpejElement As SubPej in lstEditadaPEJ Where subpejElement.PartidaEJId <>  __SINPARTIDAEJ__ 




  Try

     CFLServicioLocalSQLServerDB.GuardarInfoPEJEnDB(lstINSERT,lstUPDATE,lstIDEliminadasPEJ,psSel,lstFallas,eventoBit)   

  Catch ex As Exception
      Throw ex
  End Try

    
  Return True 

End Function

Public Function ActualizarFechaPeriodoEJ(ByVal fecha As date, ByRef sMsgError As String) As Boolean  
  return  CFLServicioLocalSQLServerDB.ActualizarFechaPeriodoEj(fecha.ToString ("yyyy-MM-dd"),sMsgError)        
End Function


Public Function ActualizarParamInter(ByRef lstParamInter As List(Of CTParamIntermediario), ByRef sMsgError As String, Optional ByRef  eventoBit As CSBitEvento  = Nothing  ) As Boolean 
Dim Resultado As Boolean = False 

   If not lstParamInter is Nothing then 
       If lstParamInter.Count > 0 then
           Resultado = CFLServicioLocalSQLServerDB.ActualizarParamInterDB (lstParamInter,sMsgError,eventoBit) 
       End If
   End If
   
   Return Resultado
End Function



Public sub ObtenerMontoRemanenteyDistribuido(ByRef lstDistribuido As List(Of SubPej), ByRef psActual As CTPartidaSolicitud, _
                                             ByRef OUTMontoRemanente As Decimal, ByRef OUTMontoDistribuido  As Decimal )

    Try

    
    OUTMontoDistribuido = 0 

    For Each Distrib As SubPej  In  lstDistribuido
        OUTMontoDistribuido += Distrib.CantidadAsigInterm 
    Next
  
    OUTMontoRemanente = psActual.CantidadSol - OUTMontoDistribuido


    Catch ex As Exception
        OUTMontoDistribuido = 0
        OUTMontoRemanente   = 0 
    End Try



End Sub




#Region "Funcionalidad  que implican NOTIFICACIONES"

    Public Function PasarPSEnviadaAEnProceso(ByRef lstPS As List(Of CTPartidaSolicitud),ByRef sMsgError As String, ByRef eventoBit As CSBitEvento) As Boolean

          sMsgError  = "" 
          Dim param  = New StringBuilder("")

          Dim lstDetBitEvento = New List(Of CTBitEventoDet )

       
           For Each ps As CTPartidaSolicitud  In lstPS
               param.Append(ps.PartidaSolId.ToString())
               param.Append(",") 
               lstDetBitEvento.Add(New CTBitEventoDet("id_PS",ps.PartidaSolId.ToString()))
           Next
           param.Remove (param.Length-1,1)


           eventoBit.GuardarDetalles (lstDetBitEvento) 

          If  CFLServicioLocalSQLServerDB.CambiarEstatusPSEnviadaAEnProcesoDB(param.ToString(),sMsgError,eventoBit) = false then 
               Return False
          else              
               Return True 
          End If
       
      
        End Function
   
    Public Function PasarPSEnProcesoALiberada(ByRef ps As CTPartidaSolicitud, Optional ByRef  eventoBit As CSBitEvento  = Nothing ) As Boolean 
       Dim sMsgError As String = ""


       eventoBit.GuadarDetalle("IdPSs",ps.PartidaSolId.ToString ()) 
       CFLServicioLocalSQLServerDB.CambiarEstatusPSEnProcesoALiberadaDB (ps.PartidaSolId.ToString (),sMsgError)  
      
       If not sMsgError.Equals ("") then
          Dim errorBit = eventoBit.GuardarError (sMsgError)        
          Return False
       Else
           Return True    
       End If

    End Function
    
    Public Function AplicarAjuste(ByRef  idPS As Long, ByRef   idPEJ As Long, ByRef  idPAJ As Long, ByRef sMsgError As String) As Boolean 
       If  CFLServicioLocalSQLServerDB.AplicarPartidaAjusteDB (idPS,idPEJ,idPAJ,sMsgError)  = False then                
           Return False 
       else
           Return True 
       End If 
    End Function

    Public Function CancelarPSDesdeEJecucion(ByVal idPs As Long, ByVal observacion As String, ByRef sMsgError As String) As Boolean 

         CFLServicioLocalSQLServerDB.CancelarPSDesdeEjecucionDB (idPs,observacion,sMsgError) 

         If not sMsgError.Equals ("") then 
            Return False
         Else
            Return True    
         End If
    End Function


#End Region



End Class
